package com.leejxx.health.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.leejxx.health.common.MessageConst;
import com.leejxx.health.entity.Result;
import com.leejxx.health.pojo.OrderSetting;
import com.leejxx.health.service.OrderSettingService;
import com.leejxx.health.vo.DateParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author LeeJx
 * @ClassName OrderSettingController
 * @Description TODO
 * @date 2021/1/3 16:35
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/orderSetting")
public class OrderSettingController {

    @DubboReference
    private OrderSettingService orderSettingService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile) {
        log.info("[excel文件处理-上传文件]文件上传:name:{},size:{}", multipartFile.getOriginalFilename(), multipartFile.getSize());

        String filename = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return new Result(false, "缺少文件名");
        }
        if (filename.endsWith(".xls") || filename.endsWith(".xlsx")) {
            return importExcel(multipartFile);
        } else {
            return new Result(false, "文件格式不正确");
        }
    }

    @RequestMapping("/findOrderSettingByDate")
    public Result findOrderSettingByDate(@RequestBody DateParam dateParam) {
        log.info("[预约设置-查询信息]年份:{},月份:{}", dateParam.getYear(), dateParam.getMonth());
        List<OrderSetting> orderSettings = orderSettingService.findOrderSetting(dateParam.getYear(), dateParam.getMonth());
        //转换成前端需要的结构
        List<Map<String, Object>> voList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            //创建用于日期处理的工具类Calendar对象
            Calendar cal = Calendar.getInstance();
            //设置时间为预约日期

            Date orderDate = null;
            try {
                orderDate = new SimpleDateFormat("yyyy-MM-dd").parse(orderSetting.getOrderDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            assert orderDate != null;
            cal.setTime(orderDate);
            Map<String, Object> map = new HashMap<>();
            //设置日期限-当月第几天
            map.put("date", cal.get(Calendar.DAY_OF_MONTH));
            //设置数量-当天允许的预约数量
            map.put("number", orderSetting.getNumber());
            //设置已经预约的人数
            map.put("reservations", orderSetting.getReservations());
            voList.add(map);
        }
        log.info("[预约设置-查询成功]data:{}", voList);
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, voList);
    }

    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody DateParam dateParam) {
        log.info("[预约设置-设置可预约人数]设置日期:{},可预约数量:{}", dateParam.getOrderDate(), dateParam.getNumber());
        orderSettingService.editNumber(dateParam.getOrderDate(), dateParam.getNumber());
        return new Result(true, MessageConst.ORDERSETTING_SUCCESS);
    }

    private Result importExcel(MultipartFile multipartFile) {
        //设置参数
        ImportParams params = new ImportParams();
        //表头设置为1行，标题行为默认为0，不设置
        params.setHeadRows(1);
        //读取全部sheet
        params.setStartSheetIndex(0);
        //开启excel校验
        params.setNeedVerify(true);
        try {
            //导入数据
            ExcelImportResult<OrderSetting> results = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(), OrderSetting.class, params);

            log.info("[excel文件处理-上传文件]是否出现校验错误数据:{}", results.isVerfiyFail());
            log.info("[excel文件处理-上传文件]检验成功的集合:{}", results.getList());

            //返回错误信息
            if (results.isVerfiyFail()) {
                StringBuilder errorDataBody = new StringBuilder();
                //log.error("[excel文件处理-上传文件]检验失败的集合:{}", results.getFailList());
                //遍历获取错误信息
                for (OrderSetting orderSetting : results.getFailList()) {
                    log.error("[excel文件处理-上传文件]第{}行的错误是{}", orderSetting.getRowNum() + 1, orderSetting.getErrorMsg());
                    errorDataBody.append("文件第").append(orderSetting.getRowNum()).append("行的错误是").append(orderSetting.getErrorMsg()).append(",");
                }
                return new Result(false, MessageConst.IMPORT_ORDERSETTING_FAIL, errorDataBody);
            }
            //存储成功信息
            orderSettingService.addAll(results.getList());

            return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
    }
}
